﻿using System;
using System.Net;
using System.Threading;
using System.Xml.Linq;
using System.Linq;
using System.Xml.XPath;

namespace SilverAmp
{
    public class LastFmSongInformationProvider : ISongInformationProvider
    {
        public event EventHandler<TrackEventArgs> SongDetailsUpdateComplete;

        private ITrackInfo original;

        private SynchronizationContext context;

        public void UpdateSongInformation(ITrackInfo song)
        {
            //context = SynchronizationContext.Current;

            //original = song;
            //var request = (HttpWebRequest)WebRequest.Create(
            var uri = string.Format( "http://ws.audioscrobbler.com/2.0/?method=track.getinfo&api_key={2}&artist={0}&track={1}",
                song.Artist ?? "", song.Name ?? "", "a0a51cdfaf17c2e402a0fd456f67f889");

            //request.BeginGetResponse(callback, request);
            WebClient wc = new WebClient();
          
            wc.OpenReadCompleted += (wc_DownloadStringCompleted);
            wc.OpenReadAsync(new Uri(uri));
        }

        void wc_DownloadStringCompleted(object sender, OpenReadCompletedEventArgs e)
        {
            var d =e.Result;
        }


        private void callback(IAsyncResult ar)
        {
            var req = (HttpWebRequest)ar.AsyncState;
            try
            {
                var response = req.EndGetResponse(ar);

                var xd = XDocument.Load(response.GetResponseStream());

                XNode node = xd.Root.FirstNode;
                TagLib.Tag tag = original.Tags;
                tag.Genres[0] = GetValue(node.XPathSelectElement("//track/toptags/tag/name[0]"));

                var trackInfo = original;
                trackInfo.BeginEdit();
                trackInfo.Artist = GetValue(node.XPathSelectElement("//track/artist/name"));
                trackInfo.Name = GetValue(node.XPathSelectElement("//track/name"));
                trackInfo.Image =
                    GetValue(node.XPathSelectElement("//track/album/image[@size='extralarge']"));
                trackInfo.Fileinfo = original.Fileinfo;
                trackInfo.Tags = tag;
                trackInfo.InfoUrl = GetValue(node.XPathSelectElement("//track/url"));
                trackInfo.EndEdit();
                InvokeSongDetailsUpdateComplete(trackInfo);

            }
            catch (System.Net.WebException e)
            {
                InvokeSongDetailsUpdateComplete(original);
            }
        }

        private string GetValue(XElement element)
        {
            return element != null ? element.Value : "";
        }

        private void InvokeSongDetailsUpdateComplete(ITrackInfo e)
        {
            EventHandler<TrackEventArgs> handler = SongDetailsUpdateComplete;
            if (handler != null)
            {
                //context.Post(delegate
                //                 {
                                     handler(this, new TrackEventArgs() { TrackInfo = e });
                              //   }, null);
            }
        }
    }
}